using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Samples.ShoppingCart;

public partial class ShoppingCart : System.Web.UI.UserControl, INamingContainer, IShoppingCart, IScriptControl
{
    public event EventHandler ArticleAdd;

    private List<IArticle> Cart
    {
        get
        {
            List<IArticle> cart = Session["Cart"] as List<IArticle>;

            if (cart == null)
            {
                cart = new List<IArticle>();
                Session["Cart"] = cart;
            }

            return cart;
        }
    }

    public override void DataBind()
    {
        repArticles.DataSource = this.Cart;
        repArticles.DataBind();
    }

    public void Add(IArticle article)
    {
        foreach (IArticle art in this.Cart)
        {
            if (art.Id == article.Id)
            {
                art.Quantity++;
                this.DataBind();
                OnArticleAdd(this, EventArgs.Empty);
                return;
            }
        }

        article.Quantity++;
        this.Cart.Add(article);
        this.DataBind();

        OnArticleAdd(this, EventArgs.Empty);
    }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        this.DataBind();
    }

    protected override void OnPreRender(EventArgs e)
    {
        ScriptManager manager = ScriptManager.GetCurrent(this.Page);

        if (manager != null)
        {
            // Register ourselves with the ScriptManager.
            manager.RegisterScriptControl(this);
        }
        else
        {
            throw new InvalidOperationException("A ScriptManager must be present on the page.");
        }
    }

    protected override void Render(HtmlTextWriter writer)
    {
        base.Render(writer);

        // Register script descriptors.
        ScriptManager.GetCurrent(this.Page).RegisterScriptDescriptors(this);
    }

    private void OnArticleAdd(object sender, EventArgs e)
    {
        if (ArticleAdd != null)
        {
            ArticleAdd(sender, e);
        }
    }

    #region IScriptControl Members

    public System.Collections.Generic.IEnumerable<ScriptDescriptor> GetScriptDescriptors()
    {
        ScriptBehaviorDescriptor desc = new ScriptBehaviorDescriptor("Samples.CartZone", shoppingCart.ClientID);

        yield return desc;
    }

    public System.Collections.Generic.IEnumerable<ScriptReference> GetScriptReferences()
    {
        ScriptReference scriptRef = new ScriptReference(Page.ResolveClientUrl("~/ScriptLibrary/CartZone.js"));

        yield return scriptRef;
    }

    #endregion
}
